package com.YJ;

//OkHttp

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.Properties;

//JSON
//Java Mail
//java配置文件

public class SendMailToMe {

    //天气接口api key
    private static final String apiKey = "4a417aba564b4f6a82ba71ab864a3035&cityname=什邡";

    /*
    主程序
     */
    public static void main(String[] args) throws Exception {
        //使用OkHttp调用接口
        OkHttpClient okHttp = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://api.avatardata.cn/Weather/Query?key=" + apiKey)
                .build();
        Response response = okHttp.newCall(request).execute();
        //JSONObject returnValue = null;
        String NowWeather = "";
        if (response.isSuccessful()) {
            //返回结果转换为JSON格式
            JSONObject returnValue = JSON.parseObject(response.body().string());
            System.out.println(returnValue);
            JSONObject result = returnValue.getJSONObject("result");
            JSONObject realTime = result.getJSONObject("realtime");
            JSONObject weather = realTime.getJSONObject("weather");
            NowWeather = "日期：" + realTime.getString("date") +
                    "\n农历：" + realTime.getString("moon") +
                    "\n星期：" + realTime.getString("week") +
                    "\n地点：" + realTime.getString("city_name") +
                    "\n天气：" + weather.getString("info") +
                    "\n温度：" + weather.getString("temperature") +
                    "\n湿度：" + weather.getString("humidity");

        }
        //邮箱的配置
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.163.com");
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");

        //使用STARTTLS,对于其它协议（如pop3，imap），只需要将smtp改为相应协议即可（pop3要改为pop）
        // 若要使用SSL，只需要设置mail.smtp.ssl.enable为true
        prop.put("mail.smtp.starttls.enable", "true");

        //使用JavaMail发送邮件的5个步骤
        //1、创建session
        Session session = Session.getInstance(prop);
        //开启Session的debug模式，便于看到发送Email的运行状态
        session.setDebug(true);
        //2、通过session得到transport对象
        Transport ts = session.getTransport();
        //3、发件邮箱的帐号和密码。
        ts.connect("18224072177@163.com", "qq18224072177");
        //4、创建邮件（Java用Message对象封装（代表）邮件），其中，最后一个参数含义：
        //（收件人<-->RecipientType.TO，抄送<-->RecipientType.CC，密送<-->RecipientType.BBC）
        Message message = CreatMail(session, "nice dream", NowWeather.toString(), Message.RecipientType.TO);
        //5、发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    }

    public static MimeMessage CreatMail(Session session, String title, String returnValue, Message.RecipientType type)
            throws Exception {
        //创建MIME邮件对象
        MimeMessage message = new MimeMessage(session);

        //指定发件人昵称
        String nick = MimeUtility.encodeText("听个笑话睡个觉", "utf-8", "B");//避免乱码

        //指明邮件的发件人
        message.setFrom(new InternetAddress(nick + "<18224072177@163.com>"));

        //指明邮件的收件人
        //message.addRecipient(type, new InternetAddress("flower.monk@foxmail.com"));
        message.addRecipient(type, new InternetAddress("1715519066@qq.com"));

        //邮件主题
        message.setSubject(title);

        //邮件的文本内容，加入一些符号让结尾美美哒(^.^)(^.^)
        message.setContent("=_=" + returnValue.substring(0, returnValue.length()) + "==>>(^.^)(^.^)么么哒!", "text/html;charset=UTF-8");

        //返回创建好的邮件对象
        return message;
    }
}